<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="开始日期:">
        <el-date-picker
          v-model="query.createTime"
          type="date"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="结束日期:">
        <el-date-picker
          v-model="query.createTimeEnd"
          type="date"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="回执状态:">
        <el-select v-model="query.checkStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in checkStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      header-row-class-name="table-row-name"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" />
    <detail ref="detail" />
  </div>
</template>

<script>
  import { queryInventoryPlanList, queryMap, inventoryPlanDelete, inventoryPlanAudit } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import Add from './components/Add'
  import moment from 'dayjs'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import Detail from './components/Detail'

  export default {
    name: 'inventoryPlan',
    components: {
      Add, Detail
    },
    data() {
      return {
        actionColWidth: 80,
        checkStatusMap: [],
        query: {
          createTime: '',
          createTimeEnd: '',
          checkStatus: ''
        },
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'planCode',
            label: '编号',
            width: 170,
            render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.planCode}</el-link>
          },
          {
            prop: 'startTime',
            label: '盘点时间',
            width: 180,
            formatter: row => {
              let msg = moment(row.startTime).format('YYYY-MM-DD') || ''
              msg = msg + '~' + moment(row.endTime).format('YYYY-MM-DD') || ''
              return msg
            }
          },
          {
            prop: 'checkUserNumber',
            label: '盘点人数',
            align: 'right'
          },
          {
            prop: 'checkBottleNumber',
            label: '盘点总瓶数',
            align: 'right',
            width: 100
          },

          {
            prop: 'checkStatus',
            label: '状态',
            render: (h, { row }) => <span>{ row.checkStatus || row.checkStatus === 0 ? formatColumnMap(this.checkStatusMap, 'value', row.checkStatus, 'desc') : '无需回执' }</span>
          },
          {
            prop: 'remark',
            label: '备注',
            width: 150
          },
          {
            prop: 'createUser',
            label: '创建人'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'auditUser',
            label: '下发人'
          },
          {
            prop: 'auditTime',
            label: '下发时间',
            width: 160,
            render: (h, { row }) => <span>{ row.auditTime && parseTime(row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.checkStatus === 1 && <el-link size='mini' underline={false} onClick={() => this.update(row, $index)}>
                    编辑
                  </el-link>}
                  {row.checkStatus === 1 && <el-link size='mini' underline={false} onClick={() => this.audit(row)}>
                    下发
                  </el-link>}
                  {row.checkStatus === 1 && <el-link size='mini' underline={false} type='danger' onClick={() => this.del(row, $index)}>
                    删除
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    created() {
      this.queryOptionsMap()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        // 开始时间结束时间都存在
        if (this.query.createTime && this.query.createTimeEnd) {
          query.createTime = moment(this.query.createTime).format()
          query.createTimeEnd = moment(this.query.createTimeEnd).format()
          if (query.createTimeEnd < query.createTime) {
            this.$message.error('起始日期不能大于结束日期')
            return
          }
          const diff = moment(this.query.createTimeEnd).diff(moment(this.query.createTime), 'days')
          if (diff > 365) {
            this.$message.warning('选择时间条件相差不能超过12个月')
            return
          }
        }
        if (!this.query.createTime && this.query.createTimeEnd) {
          query.createTimeEnd = moment(this.query.createTimeEnd).format()
          query.createTime = moment(this.query.createTimeEnd).subtract('year', 1).format()
        }

        if (this.query.createTime && !this.query.createTimeEnd) {
          query.createTime = moment(this.query.createTime).format()
          query.createTimeEnd = moment(this.query.createTime).add('year', 1).format()
        }
        const res = await queryInventoryPlanList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await mergeAsyncFunc(queryMap, { enumName: 'CheckPlanCheckStatus' })
        this.checkStatusMap = res.data // 状态
      },
      async add() {
        await this.$refs.add.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async update(row) {
        await this.$refs.add.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 下发
      audit(row, index) {
        // 说明是已结束
        const endTime = row.endTime
        if (new Date(endTime).getTime() < new Date().getTime()) {
          // 已结束
          this.$message.error('盘点计划已过期，不能下发')
          return
        }
        this.$confirm('此操作后不可恢复，确定要执行吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在下发',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          inventoryPlanAudit({ planCode: row.planCode }).then(() => {
            this.$refs.lbTable.fetch()
            this.$notify({
              title: '提示',
              message: '下发成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      del(row, index) {
        this.$confirm('此操作后不可恢复，确定要执行吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在删除',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          inventoryPlanDelete({ planCode: row.planCode }).then(() => {
            this.tableData.data.splice(index, 1)
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
          })
        })
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
